import { FindOptionsWhere } from 'typeorm';
import { Result } from '../../dto/result.type';
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { UseGuards } from '@nestjs/common';
import { GqlAuthGuard } from '../../guards/auth.guard';
import {
  CardRecordResult,
  CardRecordResults,
} from './dto/result-cardRecord.output';
import { CardRecordType } from './dto/cardRecord.type';
import { CardRecordService } from './cardRecord.service';
import { CurUserId } from '../../decorators/current-user.decorator';
import { PageInput } from '../../dto/page.input';
import { CardRecord } from './models/cardRecord.entity';
import { cardTypeType } from '../card/models/card.entity';
import dayjs from 'dayjs';
import { TimetableRecordService } from '../timetableRecord/timetableRecord.service';

@Resolver(() => CardRecordType)
@UseGuards(GqlAuthGuard)
export class CardRecordResolver {
  constructor(
    private readonly cardRecordService: CardRecordService,
    private readonly timetableRecordService: TimetableRecordService,
  ) {}

  @Query(() => CardRecordResult)
  async getCardRecordInfo(
    @Args('id') id: string,
  ): Promise<{ data?: CardRecord; message: string }> {
    const result = await this.cardRecordService.findById(id);
    if (result) {
      return {
        data: result,
        message: '获取成功',
      };
    }
    return {
      message: '用户消费卡信息不存在',
    };
  }

  @Query(() => CardRecordResults)
  async getCardRecords(
    @CurUserId() userId: string,
    @Args('page') page: PageInput,
  ): Promise<{
    data: CardRecord[];
    page: { total: number; pageSize: number; pageNum: number };
    message: string;
  }> {
    const { pageNum, pageSize } = page;
    const where: FindOptionsWhere<CardRecord> = {
      createdBy: userId,
    };
    const [results, total] = await this.cardRecordService.findCardRecords({
      start: pageNum === 1 ? 0 : (pageNum - 1) * pageSize,
      length: pageSize,
      where,
    });
    const formatResult: CardRecord[] = results.map((item) => {
      const startDate = new Date(item.startTime);
      const endDate = new Date(item.endTime);
      return {
        ...item,
        startTime: startDate.toLocaleString(),
        endTime: endDate.toLocaleString(),
      };
    }) as CardRecord[];
    return {
      data: formatResult,
      page: {
        pageNum,
        pageSize,
        total,
      },
      message: '获取成功',
    };
  }

  @Mutation(() => Result)
  async deleteCardRecord(
    @Args('id') id: string,
    @CurUserId() userId: string,
  ): Promise<Result> {
    const result = await this.cardRecordService.findById(id);
    if (result) {
      const delRes = await this.cardRecordService.deleteById(id, userId);
      if (delRes) {
        return {
          message: '删除成功',
        };
      }
      return {
        message: '删除失败',
      };
    }
    return {
      message: '用户消费卡信息不存在',
    };
  }

  @Query(() => CardRecordResults)
  async getNormalCardRecordsByCourse(
    @CurUserId() studentId: string,
    @Args('courseId') courseId: string,
  ): Promise<CardRecordResults> {
    const result = await this.cardRecordService.findNormalCardRecordsByCourse(
      studentId,
      courseId,
    );
    if (result) {
      return {
        data: result,
        message: '获取成功',
        code: true,
      };
    }
    return {
      data: null,
      message: '获取失败',
      code: false,
    };
  }

  @Mutation(() => Result, { description: '用户预约课程' })
  async reserveCourse(
    @CurUserId() studentId: string,
    @Args('courseId') courseId: string,
    @Args('cardRecordId') cardRecordId: string,
    @Args('timetableId') timetableId: string,
    @Args('orgId') orgId: string,
  ): Promise<Result> {
    const cardRecord = await this.cardRecordService.findById(cardRecordId);
    if (!cardRecord)
      return {
        message: '用户消费卡不存在',
        code: false,
      };

    //判断是否重复预约
    const [, total] = await this.timetableRecordService.findTimetableRecords({
      start: 0,
      length: 0,
      where: {
        timetableId,
        studentId,
      },
    });
    if (total !== 0) {
      return {
        code: false,
        message: '请勿重复预约同一时间段课程',
      };
    }
    // 生成预约课程记录
    const createTimetableRecord = await this.timetableRecordService.create({
      subscribeTime: new Date(),
      studentId,
      courseId,
      cardRecordId,
      timetableId,
      orgId,
    });
    if (!createTimetableRecord) {
      return {
        message: '创建课程记录失败',
        code: false,
      };
    }
    // 消除用户卡记录
    const card = JSON.parse(cardRecord.card);
    switch (card.type) {
      case cardTypeType.TIME: {
        if (cardRecord.residueTime === 0) {
          return { message: '消费卡已失效', code: false };
        } else {
          const res = await this.cardRecordService.updateById(cardRecordId, {
            residueTime: cardRecord.residueTime - 1,
          });
          if (res) {
            return {
              code: true,
              message: '创建课程记录成功',
            };
          } else {
            await this.timetableRecordService.deleteById(
              createTimetableRecord.id,
              studentId,
            );
            return {
              code: false,
              message: '去除记录失败',
            };
          }
        }
      }
      case cardTypeType.DURATION: {
        if (!dayjs().isBefore(cardRecord.endTime)) {
          return { message: '消费卡已失效', code: false };
        } else {
          return {
            code: true,
            message: '创建课程记录成功',
          };
        }
      }
    }
  }
}
